<?php

namespace app\shop\model;
use app\common\facade\Token;
use app\common\model\Account;
use app\common\model\BaseModel;
use app\common\model\ShopMemberExpire;
use app\common\model\ShopStore;
use app\common\model\ShopRecharge;
use app\common\model\ShopMember;
use app\common\model\User;
use app\common\model\ShopMemberCard;
use app\common\model\ShopUserMoneyRecord;
use think\Db;
use app\common\service\LatLngTranslate;

class ShopOrder extends BaseModel
{
    // protected $append = ['distance'];
    protected $append = ['distance'];
    
    public function getDistanceAttr($val,$data)
    {
        
        $store = session('store');
        $juli = LatLngTranslate::GetDistance($data['latitude'],$data['longitude'],$store['latitude'],$store['longitude']);
        return $juli;
    }
    
    public function recharge(){
        // return $this->belongsTo('ShopRecharge','order_id');
        return $this->belongsTo(ShopOrderRefund::class,'id','order_id');
    }

    public function user(){
        return $this->belongsTo(User::class,'uid','id');
    }

    public function memberExpire(){
        return $this->hasMany(ShopMemberExpire::class,'uid','uid');
    }

    public function good(){
        return $this->hasMany('ShopOrderGoods','order_id');
    }
    public function store(){
        return $this->belongsTo(ShopStore::class,'store_id');
    }
    public function getAddressInfoAttr($val){
        return json_decode($val,true);
    }
    public function goodsRecord(){
        return $this->hasMany('ShopOrderGoods','order_id');
    }
    public function express(){
        return $this->hasOne('ShopOrderExpress','order_id');
    }
    public function sepllOrder(){
        return $this->hasMany(ShopOrder::class,'pt_id','pt_id');
    }
    public function spell(){
        return $this->belongsTo(ShopSpell::class,'pt_id');
    }
    
    /**
     * 订单支付
     * @Author: rocky
     * 2019/12/11 18:22
     * @param $type 1微信支付，2余额支付
     * @param $order_no 订单号
     * @param $pay_money 支付金额
     * @param $transaction_id 微信流水号
     * @param $password 支付密码
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function pay($type,$order_no,$pay_money,$transaction_id='',$password =''){
        $order = self::where('status', 1)->where('order_no', $order_no)->find();
        if($order){
            Db::startTrans();
            try {
                $order->status = 5;
                if ($order['type'] == 1){
                    $order->status = 2;
                    // $order->status = 8;//用户付款下单，但是店家未接单
                }
                $order->is_pay = 1;
                $order->pay_time = date('Y-m-d H:i:s');
                $order->pay_price = $pay_money;
                $order->pay_no = $transaction_id;
                $order->save();
                //会员卡
                if ($order['type'] == 6) {
                    $card_id = ShopOrderGoods::where('order_id',$order['id'])->find()['card_id'];
                    if ($card_id) {
                        $card_info = ShopMemberCard::where('status',1)->where('id',$card_id)->find();
                        $member_info = ShopMember::where('type',$card_info['type'])->where('uid',$order['uid'])->find();
                        if ($member_info) {
                           $member_staus = true;
                        }else{
                            $member_staus = false;
                        }
                        if ($member_info['expire_time'] <= time()){
                            $order_info = self::where('order_no', $order_no)->find();
                            $data = [
                                'order_id' => $order_info['id'],
                                'overdue_num' => $member_info['total_num'] - $member_info['use_num'],
                                'uid' => $order['uid'],
                            ];
                            (new ShopMemberExpire)->save($data);
                        }
                        /*switch ($card_info['type']) {
                            case 1:
                                if ($member_staus) {
                                    $expire_time = strtotime("+ 1 week",$member_info['expire_time']);
                                    $total_num = $card_info['wash_number'] + $member_info['residue_num'];
                                }else{
                                    $expire_time = strtotime("+ 1 week");
                                    $total_num = $card_info['wash_number'];
                                }
                                break;
                            case 2:
                                if ($member_staus) {
                                    $expire_time = strtotime("+ 1 month",$member_info['expire_time']);
                                    $total_num = $card_info['wash_number'] + $member_info['residue_num'];
                                }else{
                                    $expire_time = strtotime("+ 1 month");
                                    $total_num = $card_info['wash_number'];
                                }
                                break;
                            case 3:
                                if ($member_staus) {
                                    $expire_time = strtotime("+ 3 month",$member_info['expire_time']);
                                    $total_num = $card_info['wash_number'] + $member_info['residue_num'];
                                }else{
                                    $expire_time = strtotime("+ 3 month");
                                    $total_num = $card_info['wash_number'];
                                }
                                break;
                            default:
                                if ($member_staus) {
                                    $expire_time = strtotime("+ 1 year",$member_info['expire_time']);
                                    $total_num = $card_info['wash_number'] + $member_info['residue_num'];
                                }else{
                                    $expire_time = strtotime("+ 1 year");
                                    $total_num = $card_info['wash_number'];
                                }
                                break;
                        }*/

                        if ($member_staus) {
                            $expire_time = strtotime("+".$card_info['effective_date']." day",$member_info['expire_time']);
                            //$total_num = $card_info['wash_number'] + $member_info['residue_num'];
                            $total_num = $card_info['wash_number'] + $member_info['total_num'];
                        }else{
                            $expire_time = strtotime("+".$card_info['effective_date']." day",time());
                            //$expire_time = strtotime("+ 1 week");
                            $total_num = $card_info['wash_number'];
                        }


                        if ($member_staus) {
                            $member_info->status = 1;
                            $member_info->store_id = $order['store_id'];
                            $member_info->expire_time = $expire_time;
                            $member_info->total_num = $total_num;
                            $member_info->save();
                            $member_order = self::where('order_no', $order_no)->update(['residue_num' => $total_num]);
                        }else{
                            $data = [
                                'expire_time'=> $expire_time,
                                'store_id' => $order['store_id'],
                                'type' => $card_info['type'],
                                'card_id' => $card_info['id'],
                                'total_num' => $card_info['wash_number'],
                                'use_num' => 0,
                                'uid' => $order['uid'],
                            ];
                            (new ShopMember)->save($data);
                            $member_order = self::where('order_no', $order_no)->update(['residue_num' => $card_info['wash_number']]);
                        }
                    }
                }
                //充值订单
                if ($order['type'] == 5){
                    $recharge_id = ShopOrderGoods::where('order_id',$order['id'])->value('recharge_id');
                    $recharge_info = ShopRecharge::where('id',$recharge_id)->find();
                    $res_datas = ShopUserMoneyRecord::record($recharge_info['money'],$order['uid'],"充值",1,1,"微信支付 - 订单号：{$order['order_no']}");
                }
                //微信支付
                if($type == 1){
                    Account::record($pay_money, $order['uid'],"{$order['title']}",1,0,"微信在线支付 - 订单号：{$order['order_no']}",$order['store_id'],$order['id']);
                }elseif($type == 2){
                    $user = Token::user(true);
                    if($user['money'] < $pay_money){
                        return '余额不足';
                    }
                    Account::record($pay_money, $order['uid'],"{$order['title']}",1,0,"余额支付 - 订单号：{$order['order_no']}",$order['store_id'],$order['id']);
                    if ($order['type'] == 6){
                        ShopUserMoneyRecord::record($pay_money,$order['uid'],"会员卡购买",0,true,"余额支付 - 订单号：{$order['order_no']}");
                    }else{
                        ShopUserMoneyRecord::record($pay_money,$order['uid'],"预约消费",0,true,"余额支付 - 订单号：{$order['order_no']}");
                    }
                }
                Db::commit();
                return true;
            } catch (\Exception $e) {
                Db::rollback();
                return $e->getMessage();
            }
        }else{
            return '订单不允许支付或已支付';
        }
    }
    
}
